/*

读写设备
*/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

#define BUFFER_SIZE 1024

void print_usage(const char *prog_name) {
    printf("Usage:\n");
    printf("  %s read <dev1|dev2>\n", prog_name);
    printf("  %s write <dev1|dev2> <content>\n", prog_name);
}

int main(int argc, char* argv[])
{
    if (argc < 3) {
        print_usage(argv[0]);
        return -1;
    }

    int ret = 0;
    char *operation = argv[1];
    char *device = argv[2];
    int is_write = 0;
    
    // 验证操作类型
    if (strcmp(operation, "read") == 0) {
        if (argc != 3) {
            print_usage(argv[0]);
            return -1;
        }
    } else if (strcmp(operation, "write") == 0) {
        is_write = 1;
        if (argc != 4) {
            print_usage(argv[0]);
            return -1;
        }
    } else {
        fprintf(stderr, "Invalid operation: %s\n", operation);
        print_usage(argv[0]);
        return -1;
    }

    // 构建设备路径
    char dev_path[32];
    snprintf(dev_path, sizeof(dev_path), "/dev/%s", device);

    // 打开设备
    int fd = open(dev_path, O_RDWR);
    if (fd < 0) {
        perror("Open device failed");
        return -1;
    }

    // 执行操作
    if (is_write) {
        char *content = argv[3];
        ssize_t written = write(fd, content, strlen(content));
        if (written < 0) {
            perror("Write failed");
            ret = -1;
        } else {
            printf("Write success: %zd bytes\n", written);
        }
    } else {
        char buffer[BUFFER_SIZE];
        ssize_t read_bytes = read(fd, buffer, sizeof(buffer)-1);
        if (read_bytes < 0) {
            perror("Read failed");
            ret = -1;
        } else {
            buffer[read_bytes] = '\0'; // 添加字符串结束符
            printf("Read %zd bytes: %s\n", read_bytes, buffer);
        }
    }

    close(fd);
    return ret;
}
